import React, { useState, useCallback, useEffect } from 'react'
import { StyleSheet, Text, View, Animated } from 'react-native'

// 引入图标按钮组件
import IconButton from '../button/IconButton';

const Panel = ({ children, open, onClose, title }) => {
  // 定义框的高度
  const [panelHeight] = useState(new Animated.Value(0))

  // 使用 useCallback 定义打开面板的动画方法
  const openPanel = useCallback(
    () => {
      Animated.timing(panelHeight, {
        toValue: 1,
        duration: 200,
        useNativeDriver: false
      }).start()
    },
    [panelHeight],
  )

  // 使用生命周期方法 启动时调用
  useEffect(() => {
    if (open) {
      openPanel()
    }
  }, [open, openPanel])

  return (
    <Animated.View
      style={[
        styles.panel,
        {
          height: panelHeight.interpolate({
            inputRange: [0, 1],
            outputRange: ['0%', '85%']
          })
        }
      ]}
    >
      {/* 关闭的按钮 */}
      <View style={styles.panelHeader}>
        <Text style={styles.panelText}>{title}</Text>
        <IconButton
          name='close'
          color='white'
          size={25}
          onPress={() => {
            Animated.timing(panelHeight, {
              toValue: 0,
              duration: 200,
              useNativeDriver: false
            }).start(() => {
              // 关闭动画执行完之后，触发父组件的 onClose
              onClose()
            })
          }}
        />
      </View>
      {/* 接收传过来的数据 相当于 vue 里的插槽 */}
      {children}
    </Animated.View>
  )
}

Panel.defaultProps = {
  open: false
}

export default Panel

const styles = StyleSheet.create({
  panel: {
    position: 'absolute',
    left: 0,
    bottom: 0,
    width: '100%',
    height: '85%',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15
  },
  panelHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10
  },
  panelText: {
    flex: 1,
    alignItems: 'center',
    color: 'white',
    textAlign: 'center'
  }
})
